package hied;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "WordPositions")
public class WordPositions {

	@Element(name = "absStart")
	private AvgDev absStart;

	@Element(name = "absMiddle")
	private AvgDev absMiddle;

	@Element(name = "absEnd")
	private AvgDev absEnd;

	@Element(name = "relStart")
	private AvgDev relStart;

	@Element(name = "relMiddle")
	private AvgDev relMiddle;

	@Element(name = "relEnd")
	private AvgDev relEnd;

	public WordPositions(AvgDev absStart, AvgDev absMiddle, AvgDev absEnd,
			AvgDev relStart, AvgDev relMiddle, AvgDev relEnd) {
		this.absStart = absStart;
		this.absMiddle = absMiddle;
		this.absEnd = absEnd;
		this.relStart = relStart;
		this.relMiddle = relMiddle;
		this.relEnd = relEnd;
	}

	public WordPositions() {
	}

	public AvgDev getBestPosition(float wordsCount) {
		AvgDev abs = this.getBestAbsolute(wordsCount);
		AvgDev rel = this.getBestRelative(wordsCount);
		if (abs.getStDev() < rel.getStDev()) {
			return abs;
		} else {
			return rel;
		}
	}

	private AvgDev getBestRelative(float wordsCount) {
		AvgDev best;
		if (this.absStart.getStDev() <= this.absMiddle.getStDev()) {
			best = this.absStart;
		} else {
			best = new AvgDev(this.absMiddle.getAverage() + wordsCount / 2,
					this.absMiddle.getStDev());
		}
		if (best.getStDev() > this.absEnd.getStDev()) {
			best = new AvgDev(wordsCount - this.absEnd.getAverage(),
					this.absEnd.getStDev());
		}
		return best;
	}

	private AvgDev getBestAbsolute(float wordsCount) {
		AvgDev best;
		if (this.relStart.getStDev() <= this.relMiddle.getStDev()) {
			best = this.relStart;
		} else {
			best = this.relMiddle;
		}
		if (best.getStDev() > this.relEnd.getStDev()) {
			best = this.relEnd;
		}
		if (best == this.relStart) {
			return new AvgDev(wordsCount * best.getAverage(), wordsCount
					* best.getStDev());
		} else if (best == this.relMiddle) {
			return new AvgDev(wordsCount * (0.5f + best.getAverage()),
					wordsCount * best.getStDev());
		} else {
			return new AvgDev(wordsCount * (1 - best.getAverage()), wordsCount
					* best.getStDev());
		}
	}

	@Override
	public String toString() {
		return absStart + "," + absMiddle + "," + absEnd + "," + relStart + ","
				+ relMiddle + "," + relEnd;
	}
}
